package repository

import (
	"context"

	"github.com/example/video_backend/internal/model"
	"gorm.io/gorm"
)

// CollectionRepository 收藏仓库接口
type CollectionRepository interface {
	Create(ctx context.Context, collection *model.Collection) error
	Delete(ctx context.Context, userID, videoID uint) error
	IsCollected(ctx context.Context, userID, videoID uint) (bool, error)
	GetUserCollections(ctx context.Context, userID uint, page, pageSize int) ([]*model.Collection, int64, error)
}

// collectionRepository 实现CollectionRepository接口
type collectionRepository struct {
	db *gorm.DB
}

// NewCollectionRepository 创建收藏仓库实例
func NewCollectionRepository(db *gorm.DB) CollectionRepository {
	return &collectionRepository{db: db}
}

// Create 创建收藏
func (r *collectionRepository) Create(ctx context.Context, collection *model.Collection) error {
	return r.db.WithContext(ctx).Create(collection).Error
}

// Delete 删除收藏
func (r *collectionRepository) Delete(ctx context.Context, userID, videoID uint) error {
	return r.db.WithContext(ctx).Where("user_id = ? AND video_id = ?", userID, videoID).Delete(&model.Collection{}).Error
}

// IsCollected 检查用户是否已收藏视频
func (r *collectionRepository) IsCollected(ctx context.Context, userID, videoID uint) (bool, error) {
	var count int64
	err := r.db.WithContext(ctx).Model(&model.Collection{}).Where("user_id = ? AND video_id = ?", userID, videoID).Count(&count).Error
	if err != nil {
		return false, err
	}
	return count > 0, nil
}

// GetUserCollections 获取用户的收藏列表
func (r *collectionRepository) GetUserCollections(ctx context.Context, userID uint, page, pageSize int) ([]*model.Collection, int64, error) {
	var collections []*model.Collection
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 构建查询
	query := r.db.WithContext(ctx).Where("user_id = ?", userID)

	// 查询总数
	query.Model(&model.Collection{}).Count(&total)

	// 查询分页数据
	err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&collections).Error
	if err != nil {
		return nil, 0, err
	}

	return collections, total, nil
}